__author__ = 'Ben'

import webapp2
from Model import *
from google.appengine.ext import ndb
import datetime
import logging
from protorpc import messages
from NotificationsUtils import *

class CheckExcistHandler(webapp2.RequestHandler):
     def post(self):
        allUsersWithThisNickName = User.query(User.Name == self.request.POST.get('userName'))
        if (allUsersWithThisNickName.count(10) == 0):
             self.response.out.write(json.dumps({"userID" : ""}))
        else:
            user_key = allUsersWithThisNickName.get().key
            self.response.out.write(json.dumps({"userID" : user_key.id()}))
            race_key = ndb.Key('Race', int(self.request.get('Key')))
            race = race_key.get()
            inviteNickName = self.request.POST.get('inviteNickName')
            data = {'messageType':'RACE_INVITE','Key':self.request.POST.get('Key')}
            data.update({"Key": race.key.id(), "Manager": race.Manager.get().Name,\
                        "Distance": race.Distance, "Time": str(race.StartTime),\
                        "Tags" : race.Tags, "Participants":race.NumOfParticipants,\
                        "ManagerId": race.Manager.id(), "Estimated":race.EstimatedTime})
            data.update({'inviteNickName':inviteNickName})
            logging.info(data)
            res = sendMessageToClients(messageType = 'RACE_INVITE',registration_ids = [user_key.get().RegID] ,data=data )